<template>
  <div class="github-quick-search">
    <!-- 操作提示 -->
    <el-card class="operation-hint-card" :body-style="{ padding: '15px' }">
      <div class="operation-hint">
        <p>快速查询为体验功能，搜索结果仅供参考</p>
        <p>点击"确认入库"按钮后文件信息才会正式入库进行监控</p>
      </div>
    </el-card>
    <!-- 搜索区域 -->
    <el-card class="search-card" :body-style="{ padding: '20px' }">
      <!-- 关键词输入区域 -->
      <div class="keywords-section">
        <div class="keywords-label">关键词:</div>
        <div class="keywords-input-group">
          <el-tag
            v-for="(keyword, index) in searchForm.keywords"
            :key="index"
            closable
            @close="removeKeyword(index)"
            class="keyword-tag"
            effect="plain"
          >
            {{ keyword }}
          </el-tag>
          <el-input
            v-model="newKeyword"
            placeholder="输入关键词后按回车添加"
            class="keyword-input"
            @keyup.enter="addKeyword"
            clearable
            size="default"
          />
          <el-button
            type="primary"
            size="default"
            @click="addKeyword"
            class="add-keyword-btn"
          >
            + 添加
          </el-button>
        </div>
      </div>

      <!-- 搜索表单 -->
      <DynamicForm
        ref="searchFormRef"
        v-model="dynamicFormData"
        :form-config="searchFormConfig"
        :gutter="16"
        label-width="100px"
        type="search"
        :show-buttons="false"
        class="search-form"
      />

      <!-- 高级选项 -->
      <div class="advanced-section" v-if="advancedOptionsVisible">
        <DynamicForm
          ref="advancedFormRef"
          v-model="advancedFormData"
          :form-config="advancedFormConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          :show-buttons="false"
          class="advanced-form"
        />
      </div>

      <!-- 操作按钮 -->
      <div class="search-actions">
        <el-button
          type="text"
          @click="toggleAdvancedOptions"
          class="advanced-toggle-btn"
        >
          {{ advancedOptionsVisible ? "收起高级选项" : "展开高级选项 ▼" }}
        </el-button>
        <el-button
          type="primary"
          @click="handleSearch"
          :loading="loading"
          class="search-button"
          size="default"
        >
          搜索
        </el-button>
      </div>
    </el-card>

    <!-- 搜索结果统计 -->
    <!-- <el-card
      class="stats-card"
      :body-style="{ padding: '15px' }"
      v-if="!loading && (searchResult.length > 0 || hasSearched)"
    >
      <div class="stats-container">
        <span class="stat-item">搜索结果 ({{ searchResult.length }} 条)</span>
      </div>
    </el-card> -->

    <!-- 搜索结果 -->
    <el-card
      class="results-card"
      :body-style="{ padding: '15px' }"
      v-if="!loading && searchResult.length > 0"
    >
      <DynamicTable
        ref="tableRef"
        :data="tableData"
        :columns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        :showToolbar="false"
        rowKey="id"
        border
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
      >
        <template #toolbar-left>
          <div class="results-toolbar">
            <el-button
              type="primary"
              @click="handleOpenBatchConfirm"
              :disabled="selectedItems.length === 0"
              class="batch-button"
            >
              批量确认选中的 {{ selectedItems.length }} 项
            </el-button>
          </div>
        </template>

        <!-- 仓库信息列插槽 -->
        <template #repository="{ row }">
          <div class="repository-info">
            <a
              :href="row.repository?.html_url"
              target="_blank"
              class="repo-link"
            >
              {{ row.repository?.owner?.login }}/{{
                getRepoName(row.repository?.html_url)
              }}
            </a>
          </div>
        </template>

        <!-- 文件路径列插槽 -->
        <template #file_path="{ row }">
          <div class="file-path">
            <a :href="row.html_url" target="_blank" class="file-link">
              {{ row.path }}
            </a>
          </div>
        </template>

        <!-- 匹配内容预览列插槽 -->
        <template #matched_content="{ row }">
          <div class="matched-content-preview">
            <el-tooltip
              :content="getMatchedContentPreview(row)"
              placement="top"
              :disabled="!row.matched_content"
            >
              <div class="preview-text">
                {{ getMatchedContentPreview(row) || "无匹配内容" }}
              </div>
            </el-tooltip>
          </div>
        </template>

        <!-- 操作列插槽 -->
        <template #action="{ row }">
          <div class="action-buttons">
            <el-button
              type="info"
              size="small"
              @click="handleViewMatchedContent(row)"
              class="view-button"
            >
              查看匹配内容
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleOpenConfirm(row)"
              class="confirm-button"
            >
              确认入库
            </el-button>
          </div>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 无结果提示 -->
    <el-card
      class="result-hint-card"
      :body-style="{ padding: '15px' }"
      v-if="hasSearched && !loading && searchResult.length === 0"
    >
      <div class="hint-content">
        <p class="hint-title">💡 未找到匹配的结果</p>
        <p class="hint-suggestion">您可以尝试调整搜索条件，如：</p>
        <ul class="suggestion-list">
          <li>• 使用不同的关键词组合</li>
          <li>• 调整逻辑关系（AND/OR）</li>
          <li>• 修改文件扩展名过滤</li>
          <li>• 检查正则表达式是否正确</li>
        </ul>
      </div>
    </el-card>

    <!-- 单个确认弹窗 -->
    <ConfirmDialog
      v-model="confirmDialogVisible"
      title="确认入库"
      :fields="singleConfirmFields"
      :initial-form="confirmForm"
      :rules="singleConfirmRules"
      @confirm="handleSingleConfirm"
    />

    <!-- 批量确认弹窗 -->
    <ConfirmDialog
      v-model="batchConfirmDialogVisible"
      title="批量确认入库"
      :fields="batchConfirmFields"
      :initial-form="batchConfirmForm"
      :rules="batchConfirmRules"
      @confirm="handleBatchConfirm"
    />

    <!-- 匹配内容弹窗 -->
    <el-dialog
      v-model="matchedContentDialogVisible"
      title="匹配内容"
      width="800px"
      destroy-on-close
    >
      <div class="matched-content-dialog">
        <div class="content-header">
          <div class="content-info">
            <p><strong>仓库:</strong> {{ currentMatchedContent.repository }}</p>
            <p>
              <strong>文件路径:</strong> {{ currentMatchedContent.file_path }}
            </p>
          </div>
        </div>
        <div class="code-snippet-dialog">
          <pre><code>{{ currentMatchedContent.matched_content || "无匹配内容" }}</code></pre>
        </div>
      </div>
      <template #footer>
        <el-button @click="matchedContentDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleConfirmFromDialog">
          确认入库
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { TableColumn } from "@/components/DynamicTable/types";
import ConfirmDialog from "./components/ConfirmDialog.vue";
import { githubQuickSearch, githubConfirmResults, getDepartments } from "../../servers";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";

// 搜索表单数据
const searchForm = reactive({
  keywords: [] as string[],
  logic: "AND" as "AND" | "OR",
  extensions: [] as string[],
  extensionsStr: "",
  exclude_keywords: [] as string[],
  excludeKeywordsStr: "",
  regex_pattern: "",
  per_page: 30,
});

// DynamicForm 表单数据
const searchFormRef = ref<DynamicFormInstance>();
const advancedFormRef = ref<DynamicFormInstance>();
const dynamicFormData = reactive({
  logic: "AND",
  extensionsStr: "",
});

const advancedFormData = reactive({
  regex_pattern: "",
  excludeKeywordsStr: "",
});

// 搜索表单配置
const searchFormConfig = computed<FormItemConfig[]>(() => [
  {
    key: "logic",
    name: "逻辑关系",
    type: "select",
    placeholder: "选择逻辑关系",
    params: { clearable: false },
    options: [
      { label: "AND", value: "AND" },
      { label: "OR", value: "OR" },
    ],
    col: { span: 6 },
  },
  {
    key: "extensionsStr",
    name: "文件扩展名",
    type: "input",
    placeholder: "如: yml,properties (用逗号分隔)",
    col: { span: 10 },
  },
]);

// 高级选项表单配置
const advancedFormConfig = computed<FormItemConfig[]>(() => [
  {
    key: "regex_pattern",
    name: "正则表达式",
    type: "input",
    placeholder: "如: password\\s*=\\s*.*",
    col: { span: 12 },
  },
  {
    key: "excludeKeywordsStr",
    name: "排除词",
    type: "input",
    placeholder: "如: test,example (用逗号分隔)",
    col: { span: 12 },
  },
]);

// 同步 DynamicForm 数据到 searchForm
watch(
  () => dynamicFormData.logic,
  (val) => {
    searchForm.logic = val as "AND" | "OR";
  }
);

watch(
  () => dynamicFormData.extensionsStr,
  (val) => {
    searchForm.extensionsStr = val;
    updateExtensions();
  }
);

watch(
  () => advancedFormData.regex_pattern,
  (val) => {
    searchForm.regex_pattern = val;
  }
);

watch(
  () => advancedFormData.excludeKeywordsStr,
  (val) => {
    searchForm.excludeKeywordsStr = val;
    updateExcludeKeywords();
  }
);

const newKeyword = ref("");
const advancedOptionsVisible = ref(false);
const hasSearched = ref(false);

// 搜索结果数据
const searchResult = ref<any[]>([]);

// 表格数据和配置
const tableData = ref<any[]>([]);
const tableRef = ref<any>(null);
const loading = ref(false);
const selectedItems = ref<any[]>([]);

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  total: 0,
});

// 部门选项
const departmentOptions = ref<Array<{ label: string; value: string }>>([]);

// 加载部门列表
const loadDepartments = async () => {
  try {
    const result = await getDepartments();
    if (result && typeof result === 'object' && 'departments' in result) {
      departmentOptions.value = result.departments;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取部门列表失败");
  }
};

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    label: "仓库",
    prop: "repository",
    show: true,
    key: "repository",
    minWidth: 200,
    slot: "repository",
  },
  {
    label: "文件路径",
    prop: "path",
    show: true,
    key: "file_path",
    minWidth: 250,
    slot: "file_path",
  },
  {
    label: "文件名",
    prop: "name",
    show: true,
    key: "name",
    minWidth: 150,
  },
  {
    label: "匹配内容预览",
    prop: "matched_content",
    show: true,
    key: "matched_content",
    minWidth: 300,
    slot: "matched_content",
  },
  {
    label: "大小",
    prop: "size",
    show: true,
    key: "size",
    width: 100,
    formatter: (row: any) => {
      if (!row.size) return "未知";
      const size = row.size;
      if (size < 1024) return `${size}B`;
      if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)}KB`;
      if (size < 1024 * 1024 * 1024)
        return `${(size / (1024 * 1024)).toFixed(1)}MB`;
      return `${(size / (1024 * 1024 * 1024)).toFixed(1)}GB`;
    },
  },
  {
    label: "操作",
    prop: "action",
    width: 220,
    show: true,
    key: "action",
    slot: "action",
    fixed: "right",
  },
];

// 单个确认表单配置
const confirmDialogVisible = ref(false);
const confirmForm = reactive({
  repository_url: "",
  file_path: "",
  matched_content: "",
  department: "",
});

const singleConfirmFields = computed(() => [
  {
    label: "仓库地址",
    prop: "repository_url",
    disabled: true,
    required: false,
  },
  {
    label: "文件路径",
    prop: "file_path",
    disabled: true,
    required: false,
  },
  {
    label: "责任部门",
    prop: "department",
    type: "select" as const,
    required: true,
    options: departmentOptions.value,
  },
]);

const singleConfirmRules = {
  department: [
    { required: true, message: "请选择责任部门", trigger: "change" },
  ],
};

// 批量确认表单配置
const batchConfirmDialogVisible = ref(false);
const batchConfirmForm = reactive({
  selected_count: 0,
  department: "",
});

// 匹配内容弹窗配置
const matchedContentDialogVisible = ref(false);
const currentMatchedContent = reactive({
  repository: "",
  file_path: "",
  matched_content: "",
  repository_url: "",
});

const batchConfirmFields = computed(() => [
  {
    label: "选择数量",
    prop: "selected_count",
    disabled: true,
    required: false,
  },
  {
    label: "责任部门",
    prop: "department",
    type: "select" as const,
    required: true,
    options: departmentOptions.value,
  },
]);

const batchConfirmRules = {
  department: [
    { required: true, message: "请选择责任部门", trigger: "change" },
  ],
};

// 添加关键词
const addKeyword = () => {
  const keyword = newKeyword.value.trim();
  if (keyword && !searchForm.keywords.includes(keyword)) {
    searchForm.keywords.push(keyword);
    newKeyword.value = "";
  }
};

// 删除关键词
const removeKeyword = (index: number) => {
  searchForm.keywords.splice(index, 1);
};

// 更新扩展名数组
const updateExtensions = () => {
  if (searchForm.extensionsStr.trim()) {
    searchForm.extensions = searchForm.extensionsStr
      .split(",")
      .map((ext) => ext.trim())
      .filter((ext) => ext.length > 0);
  } else {
    searchForm.extensions = [];
  }
};

// 更新排除关键词数组
const updateExcludeKeywords = () => {
  if (searchForm.excludeKeywordsStr.trim()) {
    searchForm.exclude_keywords = searchForm.excludeKeywordsStr
      .split(",")
      .map((kw) => kw.trim())
      .filter((kw) => kw.length > 0);
  } else {
    searchForm.exclude_keywords = [];
  }
};

// 切换高级选项
const toggleAdvancedOptions = () => {
  advancedOptionsVisible.value = !advancedOptionsVisible.value;
};

// 获取仓库名称
const getRepoName = (url: string) => {
  if (!url) return "";
  const match = url.match(/github\.com\/([^\/]+\/[^\/]+)/);
  return match ? match[1] : "";
};

// 获取匹配内容预览（截取前100个字符）
const getMatchedContentPreview = (row: any) => {
  if (!row.matched_content) return "";
  const content = row.matched_content.trim();
  if (content.length <= 100) return content;
  return content.substring(0, 100) + "...";
};

// 搜索
const handleSearch = async () => {
  if (searchForm.keywords.length === 0) {
    ElMessage.warning("请至少添加一个搜索关键词");
    return;
  }

  loading.value = true;
  hasSearched.value = true;
  // 清空之前的搜索结果，避免在加载过程中显示旧数据
  searchResult.value = [];
  tableData.value = [];
  try {
    // 更新扩展名和排除关键词
    updateExtensions();
    updateExcludeKeywords();

    const params: any = {
      keywords: searchForm.keywords,
      logic: searchForm.logic,
      per_page: searchForm.per_page,
    };

    if (searchForm.extensions.length > 0) {
      params.extensions = searchForm.extensions;
    }

    if (searchForm.exclude_keywords.length > 0) {
      params.exclude_keywords = searchForm.exclude_keywords;
    }

    if (searchForm.regex_pattern.trim()) {
      params.regex_pattern = searchForm.regex_pattern.trim();
    }

    const result = await githubQuickSearch(params);
    console.log(result, "resultresultresultresultresult");

    // 处理返回数据，兼容不同的数据结构
    if (result.code === 2000 && result.data) {
      // 如果返回的是数组，直接使用；如果是对象，取 items 字段
      const items = Array.isArray(result.data)
        ? result.data
        : result.data.items || result.data.results || [];

      // 处理数据，确保每个项都有唯一ID和匹配内容
      searchResult.value = items.map((item: any) => {
        // 如果没有 matched_content，尝试从 text_matches 中提取
        let matchedContent = item.matched_content || "";
        if (
          !matchedContent &&
          item.text_matches &&
          item.text_matches.length > 0
        ) {
          // 合并所有匹配的片段
          matchedContent = item.text_matches
            .map((match: any) => match.fragment)
            .join("\n...\n");
        }

        return {
          ...item,
          id: item.html_url || `${item.repository?.html_url}_${item.path}`,
          matched_content: matchedContent,
        };
      });

      // 从 result.data 中获取 total_count，如果 result.data 是对象且有 total_count 字段
      pagination.total =
        typeof result.data === "object" &&
        !Array.isArray(result.data) &&
        result.data.total_count
          ? result.data.total_count
          : result.data.total || searchResult.value.length;

      // 更新当前页数据
      updateTableData();
      pagination.currentPage = 1;
      selectedItems.value = [];
    } else {
      // 接口返回错误或数据为空
      searchResult.value = [];
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "搜索失败，请重试");
    searchResult.value = [];
    tableData.value = [];
  } finally {
    loading.value = false;
  }
};

// 刷新
const handleRefresh = () => {
  if (searchForm.keywords.length > 0) {
    handleSearch();
  } else {
    ElMessage.info("请先添加关键词进行搜索");
  }
};

// 更新表格数据（基于分页）
const updateTableData = () => {
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  tableData.value = searchResult.value.slice(start, end);
};

// 分页变更
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  updateTableData();
};

// 每页大小变更
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  updateTableData();
};

// 选择变更
const handleSelectionChange = (selection: any[]) => {
  selectedItems.value = selection;
};

// 查看匹配内容
const handleViewMatchedContent = (row: any) => {
  currentMatchedContent.repository = row.repository?.html_url
    ? `${row.repository?.owner?.login}/${getRepoName(row.repository?.html_url)}`
    : "";
  currentMatchedContent.file_path = row.path || "";

  // 优先使用 matched_content，如果没有则从 text_matches 中提取
  let matchedContent = row.matched_content || "";
  if (!matchedContent && row.text_matches && row.text_matches.length > 0) {
    matchedContent = row.text_matches
      .map((match: any) => match.fragment)
      .join("\n\n---\n\n");
  }

  currentMatchedContent.matched_content = matchedContent;
  currentMatchedContent.repository_url = row.repository?.html_url || "";
  matchedContentDialogVisible.value = true;
};

// 从匹配内容弹窗确认入库
const handleConfirmFromDialog = () => {
  matchedContentDialogVisible.value = false;
  // 找到对应的行数据
  const row = tableData.value.find(
    (item) =>
      item.repository?.html_url === currentMatchedContent.repository_url &&
      item.path === currentMatchedContent.file_path
  );
  if (row) {
    handleOpenConfirm(row);
  }
};

// 打开单个确认弹窗
const handleOpenConfirm = (row: any) => {
  confirmForm.repository_url = row.repository?.html_url || "";
  confirmForm.file_path = row.path || "";

  // 确保匹配内容正确获取
  let matchedContent = row.matched_content || "";
  if (!matchedContent && row.text_matches && row.text_matches.length > 0) {
    matchedContent = row.text_matches
      .map((match: any) => match.fragment)
      .join("\n\n---\n\n");
  }

  confirmForm.matched_content = matchedContent;
  confirmForm.department = "";
  confirmDialogVisible.value = true;
};

// 处理单个确认
const handleSingleConfirm = async (formData: any) => {
  const loadingInstance = ElLoading.service({ text: "正在确认入库..." });
  try {
    const params = {
      results: [
        {
          repository_url: formData.repository_url,
          file_path: formData.file_path,
          matched_content: formData.matched_content,
        },
      ],
      department: formData.department,
    };

    const result = await githubConfirmResults(params);

    if (result.code === 2000) {
      ElMessage.success(result.message || "确认入库成功");

      // 从搜索结果中移除已确认的项
      const resultIndex = searchResult.value.findIndex(
        (item) =>
          item.repository?.html_url === formData.repository_url &&
          item.path === formData.file_path
      );
      if (resultIndex > -1) {
        searchResult.value.splice(resultIndex, 1);
        pagination.total = searchResult.value.length;
        updateTableData();
      }
    } else {
      ElMessage.error(result.message || "确认入库失败");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "确认入库失败");
  } finally {
    loadingInstance.close();
  }
};

// 打开批量确认弹窗
const handleOpenBatchConfirm = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning("请先选择要确认的文件");
    return;
  }

  batchConfirmForm.selected_count = selectedItems.value.length;
  batchConfirmForm.department = "";
  batchConfirmDialogVisible.value = true;
};

// 处理批量确认
const handleBatchConfirm = async (formData: any) => {
  const loadingInstance = ElLoading.service({ text: "正在批量确认入库..." });
  try {
    const results = selectedItems.value.map((row) => {
      // 确保匹配内容正确获取
      let matchedContent = row.matched_content || "";
      if (!matchedContent && row.text_matches && row.text_matches.length > 0) {
        matchedContent = row.text_matches
          .map((match: any) => match.fragment)
          .join("\n\n---\n\n");
      }

      return {
        repository_url: row.repository?.html_url || "",
        file_path: row.path || "",
        matched_content: matchedContent,
      };
    });

    const params = {
      results,
      department: formData.department,
    };

    const result = await githubConfirmResults(params);

    const successCount =
      result.data?.success_count || selectedItems.value.length;
    ElMessage.success(`成功确认 ${successCount} 个文件`);

    // 从搜索结果中移除已确认的项
    const confirmedUrls = selectedItems.value.map(
      (item) => `${item.repository?.html_url}_${item.path}`
    );
    searchResult.value = searchResult.value.filter(
      (item) =>
        !confirmedUrls.includes(`${item.repository?.html_url}_${item.path}`)
    );
    pagination.total = searchResult.value.length;
    updateTableData();
    selectedItems.value = [];
  } catch (error: any) {
    ElMessage.error(error?.message || "批量确认入库失败");
  } finally {
    loadingInstance.close();
  }
};

// 初始化加载部门列表
onMounted(() => {
  loadDepartments();
});
</script>

<style scoped lang="scss">
.github-quick-search {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .page-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
    }
  }

  .search-card,
  .stats-card,
  .result-hint-card,
  .results-card,
  .operation-hint-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .keywords-section {
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #e4e7ed;

    .keywords-label {
      font-weight: 500;
      font-size: 14px;
      color: #606266;
      margin-bottom: 12px;
    }

    .keywords-input-group {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 10px;

      .keyword-tag {
        margin: 0;
        font-size: 13px;
        padding: 0 12px;
        height: 32px;
        line-height: 32px;
        background-color: #ecf5ff;
        border-color: #b3d8ff;
        color: #409eff;
        transition: all 0.3s;

        &:hover {
          background-color: #d9ecff;
        }
      }

      .keyword-input {
        flex: 1;
        min-width: 250px;
        max-width: 400px;
      }

      .add-keyword-btn {
        white-space: nowrap;
        padding: 0 20px;
      }
    }
  }

  .search-form {
    margin-bottom: 16px;
  }

  .advanced-section {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px dashed #dcdfe6;

    .advanced-form {
      margin-bottom: 0;
    }
  }

  .search-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding-top: 16px;
    border-top: 1px solid #e4e7ed;

    .advanced-toggle-btn {
      padding: 0;
      color: #409eff;
      font-size: 14px;

      &:hover {
        color: #66b1ff;
      }
    }

    .search-button {
      min-width: 120px;
      padding: 0 30px;
    }
  }

  .stats-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px 15px;
    color: #666;
    font-size: 14px;

    .stat-item {
      display: flex;
      align-items: center;
      gap: 5px;
    }
  }

  .results-toolbar {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;

    .department-select {
      width: 200px;
    }

    .batch-button {
      padding: 5px 15px;
    }
  }

  .repository-info {
    .repo-link {
      color: #409eff;
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }
  }

  .file-path {
    .file-link {
      color: #409eff;
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }
  }

  .matched-content-preview {
    .preview-text {
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 13px;
      color: #666;
      line-height: 1.5;
      cursor: pointer;
    }
  }

  .action-buttons {
    display: flex;
    gap: 8px;
    align-items: center;

    .view-button,
    .confirm-button {
      padding: 5px 12px;
    }
  }

  .matched-content-dialog {
    .content-header {
      margin-bottom: 15px;
      padding-bottom: 15px;
      border-bottom: 1px solid #e0e0e0;

      .content-info {
        p {
          margin: 8px 0;
          color: #666;
          font-size: 14px;

          strong {
            color: #333;
            margin-right: 8px;
          }
        }
      }
    }

    .code-snippet-dialog {
      max-height: 500px;
      overflow: auto;
      background-color: #f5f5f5;
      border: 1px solid #e0e0e0;
      border-radius: 4px;
      padding: 15px;

      pre {
        margin: 0;
        font-family: "Courier New", monospace;
        font-size: 13px;
        line-height: 1.6;
        white-space: pre-wrap;
        word-wrap: break-word;

        code {
          color: #333;
        }
      }
    }
  }

  .hint-content {
    color: #666;

    .hint-title {
      margin-bottom: 10px;
      font-weight: 500;
    }

    .hint-suggestion {
      margin: 10px 0;
      color: #333;
    }

    .suggestion-list {
      padding-left: 20px;
      margin: 5px 0;

      li {
        margin: 3px 0;
      }
    }
  }

  .operation-hint {
    color: #666;
    font-size: 14px;
    line-height: 1.5;
  }

  // 响应式调整
  @media (max-width: 768px) {
    .keywords-section {
      .keywords-input-group {
        .keyword-input {
          width: 100%;
          max-width: 100%;
        }
      }
    }

    .search-actions {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;

      .search-button {
        width: 100%;
      }
    }

    .results-toolbar {
      flex-wrap: wrap;

      .department-select {
        width: 100%;
      }
    }
  }
}
</style>
